package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.feign.BehaviorFeign;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@SuppressWarnings("ALL")
/**
 * @Description :
 * @author     :LD
 */
@Service
@Log4j2
public class ArticleSearchServiceImpl implements ArticleSearchService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private BehaviorFeign behaviorFeign;
    @Autowired
    private ApUserSearchService apUserSearchService;

    /**
     * 搜索文章
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        //1 检查参数
        if (dto==null || StringUtils.isBlank(dto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //如果是首页记录搜索关键字
        if (dto.getFromIndex() == 0) {
            ApUser user = AppThreadLocalUtils.getUser();
            if(user==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            }
            ApBehaviorEntry behaviorEntry = behaviorFeign.getBehaviorEntry(user.getId(), dto.getEquipmentId());
            apUserSearchService.insert(behaviorEntry.getId(), dto.getSearchWords());
        }
        //2 从es中检索数据
        SearchRequest searchRequest = new SearchRequest("app_info_article");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //根据关键字分词查询
        boolQuery.must(QueryBuilders.queryStringQuery(dto.getSearchWords()).defaultField("title").defaultOperator(Operator.OR));
        //查询小于minDate
        boolQuery.filter(QueryBuilders.rangeQuery("publishTime").lte(dto.getMinBehotTime()));
        sourceBuilder.query(boolQuery);
        //按照发布时间倒叙
        sourceBuilder.sort("publishTime", SortOrder.DESC);
        //分页
        sourceBuilder.from(0);
        sourceBuilder.size(dto.getPageSize());
        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        //3 封装结果数据
        List<Map> articleList = new ArrayList<>();
        SearchHit[] hits = searchResponse.getHits().getHits();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            Map map = JSON.parseObject(sourceAsString, Map.class);
            articleList.add(map);
        }
        return ResponseResult.okResult(articleList);
    }
}
